package cn.ywyself.extend.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

import java.io.ByteArrayInputStream;
import java.util.*;

/**
 * XML工具方法
 *
 * @author : ywyself
 * @created : 2018-10-22 10:39
 */
public class XmlUtils {

    /**
     * XML文本转map，编码类型：UTF-8
     *
     * @param xmlBytes xml内容
     * @return map对象
     * @throws DocumentException 读取错误
     */
    public static Map<String, String> toMap(byte[] xmlBytes) throws DocumentException {
        return toMap(xmlBytes, "UTF-8");
    }

    /**
     * XML文本转map
     *
     * @param xmlBytes xml内容
     * @param charset  编码类型
     * @return map对象
     * @throws DocumentException 读取错误
     */
    public static Map<String, String> toMap(byte[] xmlBytes, String charset) throws DocumentException {
        SAXReader reader = new SAXReader(false);
        InputSource source = new InputSource(new ByteArrayInputStream(xmlBytes));
        source.setEncoding(charset);
        Document document = reader.read(source);
        Iterator iterator = document.getRootElement().elementIterator();
        SortedMap<String, String> result = new TreeMap<>();
        while (iterator.hasNext()) {
            Element element = (Element) iterator.next();
            result.put(element.getName(), element.getTextTrim());
        }
        return result;
    }

    /**
     * 将Map对象转换为xml文本
     *
     * @param params 参数map
     * @return xml格式文本
     */
    public static String toXml(Map<String, String> params) {
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        StringBuilder buf = new StringBuilder();
        buf.append("<xml>\n");
        for (String key : keys) {
            buf.append("<").append(key).append(">");
            buf.append("<![CDATA[").append(params.get(key)).append("]]>");
            buf.append("</").append(key).append(">\n");
        }
        buf.append("</xml>");
        return buf.toString();
    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("app_id", "10054");
        map.put("mch_id", "1100224");
        map.put("app_key", "askjfklskldflksajflkdf");
        map.put("attach", "attach");
        map.put("body", "body");
        map.put("out_trade_no", "20181022141906998");
        map.put("total_fee", "1");
        map.put("nonce_str", String.valueOf(System.nanoTime()));
        map.put("sign", "sign");
        map.put("sign_type", "MD5");
        String xmlStr = toXml(map);
        System.out.println(xmlStr);
        try {
            System.out.println(toMap(xmlStr.getBytes()));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}
